import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import ReactECharts from 'echarts-for-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { 
  ArrowLeft,
  BarChart3,
  LineChart,
  PieChart as PieChartIcon,
  TrendingUp,
  Calendar,
  Target,
  FileText,
  Database,
  AlertCircle,
  CheckCircle,
  Clock,
  XCircle
} from 'lucide-react';
import { chartApi } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import type { Chart } from '@/types/api';

export function ChartDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [chart, setChart] = useState<Chart | null>(null);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();

  useEffect(() => {
    if (id) {
      loadChartDetail(parseInt(id));
    }
  }, [id]);

  const loadChartDetail = async (chartId: number) => {
    setLoading(true);
    try {
      const response = await chartApi.getChartById(chartId);
      if (response.code === 0) {
        setChart(response.data);
      } else {
        throw new Error(response.message);
      }
    } catch (error: any) {
      toast({
        title: "加载失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!chart) return;
    
    // 确认删除
    if (!window.confirm('确定要删除这个图表吗？删除后无法恢复。')) {
      return;
    }

    try {
      const response = await chartApi.deleteChart(chart.id);
      if (response.code === 0) {
        toast({
          title: "删除成功",
          description: "图表已删除",
        });
        // 删除成功后返回图表列表页面
        navigate('/charts');
      } else {
        throw new Error(response.message);
      }
    } catch (error: any) {
      toast({
        title: "删除失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    }
  };

  const getChartIcon = (chartType: string) => {
    switch (chartType) {
      case '柱状图':
        return <BarChart3 className="h-6 w-6" />;
      case '折线图':
        return <LineChart className="h-6 w-6" />;
      case '饼图':
        return <PieChartIcon className="h-6 w-6" />;
      default:
        return <TrendingUp className="h-6 w-6" />;
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'wait':
        return (
          <Badge className="bg-gray-100 text-gray-800 hover:bg-gray-100">
            <Clock className="h-3 w-3 mr-1" />
            等待生成
          </Badge>
        );
      case 'running':
        return (
          <Badge className="bg-blue-100 text-blue-800 hover:bg-blue-100">
            <AlertCircle className="h-3 w-3 mr-1" />
            生成中
          </Badge>
        );
      case 'success':
        return (
          <Badge className="bg-green-100 text-green-800 hover:bg-green-100">
            <CheckCircle className="h-3 w-3 mr-1" />
            生成成功
          </Badge>
        );
      case 'failed':
        return (
          <Badge className="bg-red-100 text-red-800 hover:bg-red-100">
            <XCircle className="h-3 w-3 mr-1" />
            生成错误
          </Badge>
        );
      default:
        return <Badge variant="secondary">未知</Badge>;
    }
  };

  const renderChart = (genChart: any) => {
    try {
      let chartOption;
      
      // 检查genChart是否存在
      if (!genChart) {
        return (
          <div className="bg-gray-50 p-4 rounded-lg">
            <div className="w-full h-96 bg-white rounded border flex items-center justify-center">
              <div className="text-center text-gray-500">
                <BarChart3 className="h-12 w-12 mx-auto mb-2 text-gray-400" />
                <p>暂无图表数据</p>
                <p className="text-sm">图表生成完成后将在此处显示</p>
              </div>
            </div>
          </div>
        );
      }

      // 如果genChart是对象，直接使用
      if (typeof genChart === 'object') {
        chartOption = genChart;
      } 
      // 如果genChart是字符串，尝试解析
      else if (typeof genChart === 'string') {
        try {
          // 尝试解析JSON字符串
          chartOption = JSON.parse(genChart);
        } catch (jsonError) {
          // 如果不是JSON，尝试解析JavaScript代码
          try {
            const optionMatch = genChart.match(/option\s*=\s*({[\s\S]*?});?\s*$/m);
            if (optionMatch) {
              chartOption = eval(`(${optionMatch[1]})`);
            } else {
              chartOption = eval(`(${genChart})`);
            }
          } catch (evalError) {
            console.error('图表配置解析失败:', evalError);
            throw evalError;
          }
        }
      }

      // 验证chartOption是否有效
      if (!chartOption || typeof chartOption !== 'object') {
        throw new Error('无效的图表配置');
      }

      return (
        <div className="bg-gray-50 p-4 rounded-lg">
          <div className="flex items-center justify-between mb-4">
            <h4 className="font-medium text-gray-900">图表预览</h4>
            <Badge variant="outline">ECharts</Badge>
          </div>
          <div className="w-full h-96 bg-white rounded border">
            <ReactECharts 
              option={chartOption} 
              style={{ height: '100%', width: '100%' }}
              opts={{ renderer: 'canvas' }}
            />
          </div>
          <details className="mt-4">
            <summary className="cursor-pointer text-sm text-gray-600 hover:text-gray-800">
              查看图表配置代码
            </summary>
            <pre className="mt-2 p-3 bg-gray-100 rounded text-xs overflow-x-auto">
              <code>{JSON.stringify(chartOption, null, 2)}</code>
            </pre>
          </details>
        </div>
      );
    } catch (error) {
      console.error('图表渲染错误:', error);
      return (
        <div className="bg-red-50 p-4 rounded-lg">
          <div className="w-full h-96 bg-white rounded border flex items-center justify-center">
            <div className="text-center text-red-500">
              <XCircle className="h-12 w-12 mx-auto mb-2" />
              <p>图表渲染失败</p>
              <p className="text-sm">配置解析错误: {error instanceof Error ? error.message : '未知错误'}</p>
            </div>
          </div>
        </div>
      );
    }
  };

  if (loading) {
    return (
      <div className="p-6">
        <div className="animate-pulse space-y-6">
          <div className="h-8 bg-gray-200 rounded w-1/3"></div>
          <div className="space-y-4">
            <div className="h-4 bg-gray-200 rounded w-full"></div>
            <div className="h-4 bg-gray-200 rounded w-2/3"></div>
            <div className="h-64 bg-gray-200 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  if (!chart) {
    return (
      <div className="p-6">
        <div className="text-center py-12">
          <XCircle className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">图表不存在</h3>
          <p className="text-gray-600 mb-4">请检查图表ID是否正确</p>
          <Button onClick={() => navigate('/charts')}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            返回图表列表
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button 
            variant="outline" 
            size="sm"
            onClick={() => navigate('/charts')}
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            返回
          </Button>
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-blue-100 rounded-lg">
              {getChartIcon(chart.chartType || '')}
            </div>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">
                {chart.name?.replace(/,$/, '') || '未命名图表'}
              </h1>
              <div className="flex items-center space-x-2 mt-1">
                {getStatusBadge(chart.status)}
                <span className="text-sm text-gray-500">
                  创建于 {chart.createTime}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧主要内容 */}
        <div className="lg:col-span-2 space-y-6">
          {/* 图表展示区域 */}
          {chart.status === 'success' && chart.genChart && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <BarChart3 className="h-5 w-5" />
                  <span>图表展示</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                {renderChart(chart.genChart)}
              </CardContent>
            </Card>
          )}

          {/* 分析结论 */}
          {chart.status === 'success' && chart.genResult && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <FileText className="h-5 w-5" />
                  <span>分析结论</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="prose prose-sm max-w-none">
                  <div className="whitespace-pre-wrap text-gray-700 leading-relaxed">
                    {chart.genResult}
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* 错误信息 */}
          {chart.status === 'failed' && chart.execMessage && (
            <Card className="border-red-200">
              <CardHeader>
                <CardTitle className="flex items-center space-x-2 text-red-600">
                  <XCircle className="h-5 w-5" />
                  <span>错误信息</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="bg-red-50 p-4 rounded-lg">
                  <p className="text-red-700">{chart.execMessage}</p>
                </div>
              </CardContent>
            </Card>
          )}

        </div>

        {/* 右侧信息面板 */}
        <div className="space-y-6">
          {/* 基本信息 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">基本信息</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <div className="flex items-center space-x-2 mb-2">
                  <Target className="h-4 w-4 text-gray-500" />
                  <span className="text-sm font-medium text-gray-700">分析目标</span>
                </div>
                <p className="text-sm text-gray-600 pl-6">
                  {chart.goal || '未设置分析目标'}
                </p>
              </div>

              <Separator />

              <div>
                <div className="flex items-center space-x-2 mb-2">
                  <BarChart3 className="h-4 w-4 text-gray-500" />
                  <span className="text-sm font-medium text-gray-700">图表类型</span>
                </div>
                <p className="text-sm text-gray-600 pl-6">
                  {chart.chartType?.replace(/,$/, '') || '未指定'}
                </p>
              </div>

              <Separator />

              <div>
                <div className="flex items-center space-x-2 mb-2">
                  <Calendar className="h-4 w-4 text-gray-500" />
                  <span className="text-sm font-medium text-gray-700">创建时间</span>
                </div>
                <p className="text-sm text-gray-600 pl-6">{chart.createTime}</p>
              </div>

              <Separator />

              <div>
                <div className="flex items-center space-x-2 mb-2">
                  <Calendar className="h-4 w-4 text-gray-500" />
                  <span className="text-sm font-medium text-gray-700">更新时间</span>
                </div>
                <p className="text-sm text-gray-600 pl-6">{chart.updateTime}</p>
              </div>
            </CardContent>
          </Card>

          {/* 操作按钮 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">操作</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <Button 
                className="w-full text-red-600 hover:text-red-700 hover:bg-red-50" 
                variant="outline"
                onClick={handleDelete}
              >
                删除图表
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}